const app = getApp()
const api = wx.getStorageSync('api')
let user
Page({
  data: {
    keyword: '',
    isCategory: '',
    addCarShow: false, // 加入购物车显示与隐藏
    specification: [], // 商品规格信息
    currentIndex: 0, // 当前选中加入购物车商品的序号
    sIndex: 0, // 当前选中规格
    isLogin: true
  },

  onLoad: function (options) {
    this.initData()
    // 判断是搜索跳转来，还是分类跳转来
    this.setData({
      keyword: options.keyword,
      isCategory: options.isCategory
    })
    this.getGoodsList()
  },

  initData() {
    user = wx.getStorageSync('user')
    console.log(typeof wx.getStorageSync('user'), user)
    if (typeof user != 'object') {
      this.setData({
        isLogin: false
      })
      return
    }
    this.setData({
      user: user
    })
  },

  /**
   * 获取商品列表
   */
  getGoodsList() {
    let isCategory = this.data.isCategory == 1 ? true : false
    if (isCategory) {
      let url = api.cateGoods + `?categoryId=${this.data.keyword}`
      app.$http.get(url).then(res => {
        // console.log(res)
        this.setData({
          keyword: '',
          isCategory: 0,
          ...res.data
        })
      })
    } else if (!isCategory) {
      let url = api.search + `?name=${this.data.keyword}`
      app.$http.get(url).then(res => {
        // console.log(res)
        this.setData({
          ...res.data
        })
      })
    }
  },

  // 搜索框输入内容
  onChange(e) {
    this.setData({
      keyword: e.detail
    });
  },

  // 提交搜索
  onSearch(e) {
    this.getGoodsList()
  },

  // 商品规格点击
  sIndexClick(e) {
    this.setData({
      sIndex: e.currentTarget.dataset.index
    })
  },

  // 关闭加入购物车
  closeAddCarCard() {
    this.setData({
      addCarShow: false
    });
  },

  // 显示加入购物车
  showAddCarCard(e) {
    if (!this.data.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
      return
    }
    this.setData({
      addCarShow: true
    })
    let id = e.currentTarget.dataset.id
    let index = e.currentTarget.dataset.index
    this.setData({
      currentIndex: index
    })
    wx.request({
      url: serverUrl + '/shop/goods/getById/' + id,
      success: res => {
        res = res.data
        this.setData({
          specification: res.data.specification
        })
      }
    })
  },

  // 跳转商品详情页
  toGoodPage(e) {
    let id = e.currentTarget.dataset.id
    console.log(id)
    wx.navigateTo({
      url: `/pages/goodPage/goodPage?id=${id}`
    })
  }
})